exports 和 module.exports 的区别

Author Avatar
Klein 8月 16, 2018

ECMAScript的变量值类型共有两种:

基本类型 (primitive values) : 包括Undefined, Null, Boolean, Number和String五种基本数据类型;

引用类型 (reference values) : 保存在内存中的对象们,不能直接操作,只能通过保存在变量中的地址引用对其进行操作。

exportsmodule.exports 就是 Object 类型,属于引用类型。

exports 其实就是 module.exports 的引用。

1
var exports = module.exports;

平时我们可以这样使用:

1
2
3
4
5
6
7
exports.area = function (r) {
return Math.PI * r * r;
};

exports.circumference = function (r) {
return 2 * Math.PI * r;
};

注意,不能直接将exports变量指向一个值,因为这样等于切断了exports与module.exports的联系。

1
exports = function(x) {console.log(x)};

上面这样的写法是无效的,因为 exports 不再指向 module.exports 了。

下面的写法也是无效的。

1
2
3
4
5
exports.hello = function() {
return 'hello';
};

module.exports = 'Hello world';

上面代码中,hello函数是无法对外输出的,因为module.exports被重新赋值了。

这意味着,如果一个模块的对外接口,就是一个单一的值,不能使用exports输出,只能使用module.exports输出。

1
2
3
4
5
// 正确的写法
module.exports = function (x){ console.log(x);};

// 错误的写法
exports = function (x){ console.log(x);};

如果觉得,分不清exports与module.exports,可以选择放弃使用exports,只使用module.exports。